package com.lagou.factory;

import com.lagou.annotation.Autowired;
import com.lagou.annotation.Service;
import com.lagou.utils.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author: lcz
 * @date: Created in 15:03 2020/10/5
 * @description:
 */
@Service("proxyFactory")
public class ProxyFactory {
    @Autowired
    private TransactionManager transactionManager;

    /**
     * @param obj 委托对象
     * @author: lcz
     * @date: Created in 15:05 2020/10/5
     * @description: jdk动态代理
     */
    public Object getJdkProxy(Object obj) {
        return Proxy.newProxyInstance(this.getClass().getClassLoader(), obj.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                try {
                    //开启事务
                    transactionManager.begin();
                    Object result = method.invoke(obj, args);
                    //事务提交
                    transactionManager.commit();
                    return result;
                } catch (Exception e) {
                    e.printStackTrace();
                    //事务回滚
                    transactionManager.rollback();
                    throw e;
                }
            }
        });
    }

    /**
     * @param obj 委托对象
     * @author: lcz
     * @date: Created in 15:45 2020/10/5
     * @description: cglib动态代理
     */
    public Object getCglibProxy(Object obj) {
        return Enhancer.create(this.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                try {
                    //开启事务
                    transactionManager.begin();
                    Object result = method.invoke(obj, objects);
                    //事务提交
                    transactionManager.commit();
                    return result;
                } catch (Exception e) {
                    e.printStackTrace();
                    //事务回滚
                    transactionManager.rollback();
                    throw e;
                }
            }
        });
    }
}
